<?php

class ClassCourseQueryController extends GxController {

    public function actionCreate() {
        $model = new ClassCourseQuery;
        if (Yii::app()->request->isAjaxRequest) {
            if (isset($_POST['ClassCourseQuery'])) {
                $model->attributes = $_POST['ClassCourseQuery'];
                if (!empty($_POST['ClassCourseQuery']['classes_id'])) {
                    $model->setAttribute('classes_id', $_POST['ClassCourseQuery']['classes_id']);
                    $classes = Classes::model()->findByPk($_POST['ClassCourseQuery']['classes_id']);
                    $classCourseName = $classes->class_titile;
                }
                if (!empty($_POST['ClassCourseQuery']['courses_id'])) {
                    $model->setAttribute('courses_id', $_POST['ClassCourseQuery']['courses_id']);
                    $courses = Courses::model()->findByPk($_POST['ClassCourseQuery']['courses_id']);
                    $classCourseName = $courses->course_titile;
                }


                $valid = $model->validate();
                if ($valid) {
                    $model->save(false);
                    $mailmodel = EmailTemplate::model()->findByPk(Message::QUERY_ABOUT_CLASS);
                    $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');                  
                    $mailto = EMAIL_TO_ADMIN;
                    $arrayFind = array('[username]', '[name]', '[email]', '[message]');
                    $arrayReplace = array(EMAIL_TO_ADMIN, $_POST['ClassCourseQuery']['queryuser_name'], $_POST['ClassCourseQuery']['queryuser_email'], $_POST['ClassCourseQuery']['query_message']);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                        echo CJSON::encode(array(
                            'status' => 'success'
                        ));
                        Yii::app()->end();
                    } catch (Exception $e) {
                        echo $e;
                        exit;
                    }
                } else {
                    $error = CActiveForm::validate($model);
                    if ($error != '[]')
                        echo $error;
                    Yii::app()->end();
                }
            }
        }
    }

}
